package com.weilx959.spt.app.context;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONWriter;
import com.alibaba.fastjson2.TypeReference;
import com.weilx959.spt.core.constants.CommonConstants;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 插件配置上下文
 *
 * @author weilx
 * @since 2024-04-20
 */
@Slf4j
public class PluginConfigurationContext {
    private static final Map<String, Map<String, String>> CONFIG_MAP = new ConcurrentHashMap<>();

    private PluginConfigurationContext() {
        // prevent instantiation
    }

    public static Map<String, Map<String, String>> getAll() {
        return CONFIG_MAP;
    }

    public static Map<String, String> get(String id) {
        return  CONFIG_MAP.get(id);
    }

    public static void remove(String id) {
        CONFIG_MAP.remove(id);
    }

    public static void setAll(Map<String, Map<String, String>> configMap) {
        CONFIG_MAP.clear();
        CONFIG_MAP.putAll(configMap);
    }

    public static void set(String id, Map<String, String> config) {
        CONFIG_MAP.put(id, config);
    }

    public static void load() throws IOException {
        Path fielPath = Paths.get(CommonConstants.DEFAULT_APP_PATH, CommonConstants.PLUGINS_CONFIG_FILE);

        if (!fielPath.toFile().exists()) {
            return;
        }
        String pluginConfigString = Files.readString(fielPath, StandardCharsets.UTF_8);
        log.info("load plugin config: {}", pluginConfigString);
        if (StringUtils.isNotBlank(pluginConfigString)) {
            setAll(JSON.parseObject(pluginConfigString, new TypeReference<>() {}));
        }
    }

    public static void save() throws IOException {
        Files.writeString(Paths.get(CommonConstants.DEFAULT_APP_PATH, CommonConstants.PLUGINS_CONFIG_FILE),
            JSON.toJSONString(PluginConfigurationContext.getAll(), JSONWriter.Feature.PrettyFormat),
            StandardCharsets.UTF_8, StandardOpenOption.CREATE, StandardOpenOption.TRUNCATE_EXISTING);
    }
}
